package com.tust.androidreader;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class BookActivity extends AppCompatActivity {
    private Toast toast;
    private boolean menuIsHide;
    private String strBookname;
    private String userName;
    private List<String> bookPageList;
    private int currentPageNum = 0;
    private boolean isUpperPage;

    ScrollView scrollViewBookPage;
    TextView textViewUpperBar;
    LinearLayout linearLayoutUnderBar;
    TextView textViewBookPageUpper;
    TextView textViewPageBorder;
    TextView textViewBookPageLower;
    TextView textViewCurrentPageNum;
    TextView textViewBookPercent;
    Button buttonLastPage;
    Button buttonNextPage;
    Button buttonLike;
    LinearLayout linearLayoutCommentArea;
    TextView textViewCommentMask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();//隐藏标题导航栏
        menuIsHide = true;//记录标题栏状态
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去除时间和电量等状态栏
        setContentView(R.layout.activity_book);

        scrollViewBookPage = this.findViewById(R.id.sv_bookpage);
        textViewUpperBar = this.findViewById(R.id.tv_upperbar);
        linearLayoutUnderBar = this.findViewById(R.id.linear_underbar);
        textViewBookPageUpper = this.findViewById(R.id.tv_bookpageupper);
        textViewPageBorder = this.findViewById(R.id.tv_pageborder);
        textViewBookPageLower = this.findViewById(R.id.tv_bookpagelower);
        buttonLastPage = this.findViewById(R.id.bt_lastpage);
        buttonNextPage = this.findViewById(R.id.bt_nextpage);
        buttonLike = this.findViewById(R.id.bt_like);
        linearLayoutCommentArea = this.findViewById(R.id.linear_commentarea);
        textViewCommentMask = this.findViewById(R.id.tv_commentmask);

        buttonLastPage.setBackgroundColor(Color.rgb(153, 217, 234));
        buttonNextPage.setBackgroundColor(Color.rgb(153, 217, 234));
        buttonLike.setBackgroundColor(Color.rgb(255,174,201));

        strBookname = this.getIntent().getStringExtra("bookname");
        userName = this.getIntent().getStringExtra("username");

        DBHelper dbHelper = new DBHelper(this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        db.execSQL("update book set readtimes = readtimes + 1 where bookname = ?", new Object[]{strBookname});//更新数据库，点击数+1

        Cursor bookCursor = db.rawQuery("select * from book where bookname = ?", new String[]{strBookname});
        bookPageList = initDatas(bookCursor);
        currentPageNum = getBookPage(bookCursor);
        bookCursor.close();

        textViewBookPageUpper.setText("\n");//bookPage初始化
        textViewBookPageLower.setText(bookPageList.get(currentPageNum));
        setBookUnderInfo();

        textViewBookPageUpper.setOnClickListener(new View.OnClickListener() {//点击bookpage显示底部按钮栏、菜单栏、上部遮挡栏
            @Override
            public void onClick(View view) {
                isUpperPage = true;

                linearLayoutCommentArea.setVisibility(view.GONE);//关闭评论区
                textViewCommentMask.setVisibility(view.GONE);

                if (menuIsHide) {
                    getSupportActionBar().show();
                    getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_FULLSCREEN);//显示系统状态栏
                    textViewUpperBar.setVisibility(View.VISIBLE);
                    linearLayoutUnderBar.setVisibility(view.VISIBLE);
                    menuIsHide = false;
                } else {
                    getSupportActionBar().hide();
                    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去除时间和电量等状态栏
                    textViewUpperBar.setVisibility(View.GONE);
                    linearLayoutUnderBar.setVisibility(view.GONE);
                    menuIsHide = true;
                }
            }
        });

        textViewBookPageLower.setOnClickListener(new View.OnClickListener() {//点击bookpage显示底部按钮栏、菜单栏、上部遮挡栏
            @Override
            public void onClick(View view) {
                isUpperPage = false;

                linearLayoutCommentArea.setVisibility(view.GONE);//关闭评论区
                textViewCommentMask.setVisibility(view.GONE);

                if (menuIsHide) {
                    getSupportActionBar().show();
                    getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_FULLSCREEN);//显示系统状态栏
                    textViewUpperBar.setVisibility(View.VISIBLE);
                    linearLayoutUnderBar.setVisibility(view.VISIBLE);
                    menuIsHide = false;
                } else {
                    getSupportActionBar().hide();
                    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去除时间和电量等状态栏
                    textViewUpperBar.setVisibility(View.GONE);
                    linearLayoutUnderBar.setVisibility(view.GONE);
                    menuIsHide = true;
                }
            }
        });

        buttonLastPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isUpperPage) {
                    currentPageNum--;
                    if (getLastPage()) {
                        textViewBookPageLower.setText(bookPageList.get(currentPageNum));
                        if (getLastPage()) {
                            textViewBookPageUpper.setText(bookPageList.get(currentPageNum));
                            currentPageNum++;
                        } else {
                            textViewBookPageUpper.setText("\n");
                            isUpperPage = false;
                        }
                        scrollViewBookPage.scrollTo(0,0);
                    } else {
                        currentPageNum++;
                        showToast("没有上一页！");
                    }
                } else {
                    if (getLastPage()) {
                        textViewBookPageLower.setText(bookPageList.get(currentPageNum));
                        if (getLastPage()) {
                            textViewBookPageUpper.setText(bookPageList.get(currentPageNum));
                            currentPageNum++;
                        } else {
                            textViewBookPageUpper.setText("\n");
                            isUpperPage = false;
                        }
                        scrollViewBookPage.scrollTo(0,0);
                    } else {
                        showToast("没有上一页！");
                    }
                }
            }
        });

        buttonNextPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentPageNum == bookPageList.size() - 1) {
                    isUpperPage = false;
                }

                if (isUpperPage) {
                    currentPageNum--;
                    if (getNextPage()) {
                        textViewBookPageUpper.setText(bookPageList.get(currentPageNum));
                        if (getNextPage()) {
                            textViewBookPageLower.setText(bookPageList.get(currentPageNum));;
                        } else {
                            textViewBookPageLower.setText("");
                            isUpperPage = false;
                        }
                        scrollViewBookPage.scrollTo(0,0);
                    } else {
                        showToast("没有下一页！");
                    }
                } else {
                    if (getNextPage()) {
                        textViewBookPageUpper.setText(bookPageList.get(currentPageNum));
                        if (getNextPage()) {
                            textViewBookPageLower.setText(bookPageList.get(currentPageNum));
                        } else {
                            textViewBookPageLower.setText("");
                            isUpperPage = false;
                        }
                        scrollViewBookPage.scrollTo(0,0);
                    } else {
                        showToast("没有下一页！");
                    }
                }
            }
        });

        buttonLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                db.execSQL("update book set likenum = likenum + 1 where bookname = ?", new Object[]{strBookname});//更新数据库，点赞数+1

                showToast("Like + 1！");
            }
        });

        /*scrollViewBookPage.onScrollViewScrollToBottom(new ScrollLoadScrollView.OnScrollBottomListener() {
            @Override
            public void scrollToBottom() {
                buttonNextPage.performClick();
            }
        });*/

        /*scrollViewBookPage.onScrollViewScrollToTop(new ScrollLoadScrollView.OnScrollTopListener() {
            @Override
            public void scrollToTop() {
                buttonLastPage.performClick();
            }
        });*/

        scrollViewBookPage.setOnTouchListener(new View.OnTouchListener() {//触摸时的监听器
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {//监听滑动到头部与底部
                    case MotionEvent.ACTION_UP: {/*原来是ACTION_MOVE，会造成方法重复调用*/
                        /*if (scrollViewBookPage.getScrollY() <= 0) {//说明没有滑动，在屏幕顶部
                            showToast("已在顶部,翻到上一页");
                            buttonLastPage.performClick();
                        }*/

                        int measuredHeight = scrollViewBookPage.getChildAt(0).getMeasuredHeight();//获取ScrollView的控件高度
                        int scrollY = scrollViewBookPage.getScrollY();//获取滑动距离
                        int height = scrollViewBookPage.getHeight();//获取ScrollView在屏幕中的显示高度

                        if (measuredHeight <= scrollY + height) {//控件真实高度 <= 已经滑动的距 离 + 在屏幕上显示的高度，说明已经滑动到ScrollView底部
                            if (getNextPage()) {
                                textViewBookPageUpper.setText(bookPageList.get(currentPageNum - 1));
                                textViewBookPageLower.setText(bookPageList.get(currentPageNum));

                                scrollViewBookPage.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        scrollViewBookPage.scrollTo(0, textViewPageBorder.getTop() - height);
                                    }
                                });

                                //showToast("下一页");
                            } else {
                                showToast("没有下一页！");
                            }
                        }
                        break;
                    }
                    default: break;
                }
                return false;
            }
        });
    }

    private int getBookPage(Cursor cursor) {//获得阅读进度
        cursor.moveToFirst();
        int bookPage = cursor.getInt(10);
        return bookPage;
    }

    private boolean getLastPage() {
        int lastPageNum;
        lastPageNum = currentPageNum - 1;
        if (lastPageNum < 0) {
            return false;
        } else {
            currentPageNum = lastPageNum;
            setBookUnderInfo();
            return true;
        }
    }

    private boolean getNextPage() {
        int nextPageNum;
        nextPageNum = currentPageNum + 1;
        if (nextPageNum > bookPageList.size() - 1) {
            return false;
        } else {
            currentPageNum = nextPageNum;
            setBookUnderInfo();
            return true;
        }
    }

    private void setBookUnderInfo() {
        textViewCurrentPageNum = this.findViewById(R.id.tv_currentpagenum);
        String textViewBookPercentContent = "第" + String.valueOf(currentPageNum + 1) + "页";
        textViewCurrentPageNum.setText(textViewBookPercentContent);

        textViewBookPercent = this.findViewById(R.id.tv_bookpercent);
        double bookPercentNum = (double)currentPageNum / (bookPageList.size() - 1) * 100;
        if (currentPageNum == 0) {
            textViewBookPercent.setText("0.00%");
            return;
        }
        textViewBookPercent.setText((new java.text.DecimalFormat("#.00").format(bookPercentNum)) + "%");
    }

    private List initDatas(Cursor cursor) {//文本文件最好保存为GB2312，以解决乱码
        List<String> list = new ArrayList();
        int maxWord = 1000;//每块最小字数
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        
        cursor.moveToFirst();
        if (cursor.getString(9).charAt(0) == 'd') {//是用户自己添加的
            cursor.moveToFirst();
            String bookContentAddress = cursor.getString(9);

            File file = new File(bookContentAddress);
            try {
                inputStream = new FileInputStream(file);
                inputStreamReader =  new InputStreamReader(inputStream, getCharset(file));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {//是示例文本
            cursor.moveToFirst();
            int bookContentID = cursor.getInt(9);//获取文本资源地址id

            Resources res = super.getResources();
            inputStream = res.openRawResource(bookContentID);
            try {
                inputStreamReader = new InputStreamReader(inputStream, "GB2312");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        /*****************************写入内存储的Test*******************************/
        /*File fileSave = new File("data/data/com.tust.androidreader/a.txt");
        try {
            OutputStream outputStream = new FileOutputStream(fileSave);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "GB2312");
            int c;
            while ((c = inputStreamReader.read()) != -1)
            {
                outputStreamWriter.write(c);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();
            inputStreamReader.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        /**************************************************************************/

        StringBuffer stringBuffer = new StringBuffer();//接收数据

        try {//以固定编码读取文件
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;//保存读取到的内容
            while ((line = bufferedReader.readLine()) != null) {//循环读取
                stringBuffer.append("\t\t\t\t" + line + "\n");//保存数据
                if (stringBuffer.length() > maxWord) {
                    list.add(String.valueOf(stringBuffer));//保证每页差不多长度
                    stringBuffer.setLength(0);//清空缓冲区
                    maxWord = 1000;
                }
            }
            list.add(String.valueOf(stringBuffer));///最后不足1000字的提交

            bufferedReader.close();
            inputStream.close();
            inputStreamReader.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //旧方法，会导致乱码，listadd有问题，文章 < 1000会报错
        /*Scanner scanner = new Scanner(inputStream);
        while (scanner.hasNext()) {
            while (scanner.hasNext() && stringBuffer.length() < maxWord) {//循环读取
                stringBuffer.append("\t\t\t\t" + scanner.nextLine() + "\n");//保存数据
            }
            list.add(String.valueOf(stringBuffer));
            stringBuffer.setLength(0);//清空缓冲区
            maxWord = 1000;
        }
        scanner.close();//关闭输入流*/
        return list;
    }

    public String getCharset(File file) {//获取文件编码类型
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        try {
            boolean checked = false;
            InputStream is = new FileInputStream(file);
            int read = is.read(first3Bytes, 0, 3);

            if (read == -1)
                return charset;
            //Log.i(TAG,"[GetCharset]first3Bytes[0]:"+first3Bytes[0]+", first3Bytes[1]:"+first3Bytes[1]+",first3Bytes[2]:"+first3Bytes[2]);
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE
                    && first3Bytes[1] == (byte) 0xFF) {
                charset = "UTF-16BE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF
                    && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8";
                checked = true;
            }else if (first3Bytes[0] == (byte) 0xA
                    && first3Bytes[1] == (byte) 0x5B
                    && first3Bytes[2] == (byte) 0x30) {
                charset = "UTF-8";
                checked = true;
            }else if (first3Bytes[0] == (byte) 0xD
                    && first3Bytes[1] == (byte) 0xA
                    && first3Bytes[2] == (byte) 0x5B) {
                charset = "GBK";
                checked = true;
            }else if (first3Bytes[0] == (byte) 0x5B
                    && first3Bytes[1] == (byte) 0x54
                    && first3Bytes[2] == (byte) 0x49) {
                charset = "windows-1251";
                checked = true;
            }
            //bis.reset();
            InputStream istmp = new FileInputStream(file);
            if (!checked) {
                int loc = 0;
                while ((read = istmp.read()) != -1) {
                    loc++;
                    if (read >= 0xF0)
                        break;
                    if (0x80 <= read && read <= 0xBF)
                        break;
                    if (0xC0 <= read && read <= 0xDF) {
                        read = istmp.read();
                        if (0x80 <= read && read <= 0xBF)
                            continue;
                        else
                            break;
                    } else if (0xE0 <= read && read <= 0xEF) {
                        read = istmp.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = istmp.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
            }
            is.close();
            istmp.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return charset;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {//创建菜单
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {//菜单选项处理
        super.onOptionsItemSelected(item);
        switch(item.getItemId())//得到被点击的item的itemId
        {
            case  R.id.menu_comment:
                LinearLayout linearLayoutCommentArea = this.findViewById(R.id.linear_commentarea);
                Button buttonBackToBook = this.findViewById(R.id.bt_backtobook);
                TextView textViewCommentMask = this.findViewById(R.id.tv_commentmask);
                TextView textViewComment = this.findViewById(R.id.tv_comment);
                EditText editTextYourComment = this.findViewById(R.id.et_yourcomment);
                ImageView imageViewSendComment = this.findViewById(R.id.iv_sendcomment);

                linearLayoutCommentArea.setVisibility(View.VISIBLE);
                textViewCommentMask.setVisibility(View.VISIBLE);

                textViewComment.setText(initCommentDatas());

                buttonBackToBook.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        linearLayoutCommentArea.setVisibility(view.GONE);
                        textViewCommentMask.setVisibility(view.GONE);
                    }
                });

                imageViewSendComment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String yourComment = editTextYourComment.getText().toString();

                        if (yourComment.equals("")) {
                            showToast("评论不能为空！");
                        } else if (yourComment.equals("请输入您的评论")) {
                            showToast("请输入您的评论！");
                        } else {//存入comment数据表
                            DBHelper dbHelper = new DBHelper(view.getContext());
                            SQLiteDatabase db = dbHelper.getWritableDatabase();

                            try {
                                db.execSQL("insert into comment (bookname, username, comment) values (?, ?, ?)", new Object[]{strBookname, userName, yourComment});
                                db.execSQL("update book set commentnum = commentnum + 1 where bookname = ?", new Object[]{strBookname});//更新数据库，评论数+1
                                showToast("评论成功！");
                            } catch (Exception exception) {
                                showToast("评论失败！");
                                exception.printStackTrace();
                            }

                            textViewComment.setText(initCommentDatas());

                            editTextYourComment.setText("");
                        }
                    }
                });
                break;
            case R.id.menu_back:
                Intent intent = new Intent(BookActivity.this, LibraryActivity.class);
                startActivity(intent);
                break;
        }
        return true;
    }

    private  String initCommentDatas() {
        String comments = "";
        String comment;
        String userName;

        DBHelper dbHelper = new DBHelper(this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        Cursor commentCursor = db.rawQuery("select * from comment where bookname = ?", new String[]{strBookname});

        commentCursor.moveToFirst();
        while (!commentCursor.isAfterLast()) {//游标只要不是在最后一行之后，就一直循环
            userName = commentCursor.getString(2);
            comment = commentCursor.getString(3);

            comments = comments + userName + "：" + comment + "\n\n";

            commentCursor.moveToNext();//将游标移到下一行
        }

        commentCursor.close();
        return comments;
    }

    @Override
    public void onBackPressed() {//返回时记录阅读进度，并重新加载书架
        super.onBackPressed();

        //if (currentPageNum == 1) currentPageNum = 0;

        DBHelper dbHelper = new DBHelper(this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        db.execSQL("update book set currentpage = ? where bookname = ?", new Object[]{currentPageNum, strBookname});//更新数据库，记录阅读进度，下次阅读直接进入

        Intent intent = new Intent(BookActivity.this, LibraryActivity.class);//重新加载LibraryActivity
        startActivity(intent);
    }

    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}